<template>
  <div id="pieContainer"></div>
</template>

<script setup>
import G6 from "@antv/g6";
import { onMounted } from "vue";

const lightBlue = "#5b8ff9";
const lightOrange = "#5ad8a6";

onMounted(() => {
  G6.registerNode("pie-node", {
    draw(cfg, group) {
      const radius = cfg.size / 2;
      const inPrecentage = cfg.inDegree / cfg.degree;
      const inAngle = inPrecentage * Math.PI * 2;
      const inArcEnd = [
        radius * Math.cos(inAngle),
        -radius * Math.sin(inAngle),
      ];
      let isInBigArc = 0,
        isOutBigArc = 1;
      if (inAngle > Math.PI) {
        isInBigArc = 1;
        isOutBigArc = 0;
      }

      const fanIn = group.addShape("path", {
        attrs: {
          path: [
            ["M", radius, 0],
            ["A", radius, radius, 0, isInBigArc, 0, inArcEnd[0], inArcEnd[1]],
            ["L", 0, 0],
            ["Z"],
          ],
          lineWidth: 0,
          fill: lightOrange,
        },
        name: "in-fan-shape",
      });
      group.addShape('path', {
        attrs: {
            path: [
                ['M', inArcEnd[0], inArcEnd[1]],
                ['A', radius, radius, 0, isOutBigArc, 0, radius, 0],
                ['L', 0, 0],
                ['Z']
            ],
            lineWidth: 0,
            fill: lightBlue
        },
        name: 'out-fan-shape'
      })
      group.addShape("text", {
        attrs: {
          text: cfg.id,
          fontSize: 16,
          textAlign: "center",
          textBaseline: "middle",
          fill: 'red'
        },
        name: 'pei-label'
      });
      return fanIn;
    },
  });
  const data = {
    nodes: [
      {
        id: "pie1",
        size: 80,
        inDegree: 80,
        degree: 360,
        x: 150,
        y: 150,
      },
      {
        id: "pie2",
        size: 80,
        inDegree: 280,
        degree: 360,
        x: 350,
        y: 150,
      },
    ],
    edges: [
      {
        source: "pie1",
        target: "pie2",
      },
    ],
  };
  const container = document.getElementById("pieContainer");
  const width = container.scrollWidth;
  const height = container.scrollHeight || 500;
  const graph = new G6.Graph({
    container: "pieContainer",
    width,
    height,
    fitCenter: true,
    linkCenter: true,
    defaultNode: {
      type: "pie-node",
    },
  });
  graph.data(data);
  graph.render();
  if (typeof window !== "undefined") {
    window.onresize = () => {
      if (!graph || graph.get("destroyed")) return;
      if (!container || !container.scrollWidth || !container.scrollHeight)
        return;
      graph.changeSize(container.scrollWidth, container.scrollHeight);
    };
  }
});
</script>

<style lang="less" scoped></style>
